<script setup lang="ts">
import { ref, markRaw, computed } from "vue";

import { useColumns } from "./activity_columns";
import "plus-pro-components/es/components/search/style/css";
import Plus from "~icons/ep/plus";
import Delete from "~icons/ep/delete";
import "plus-pro-components/es/components/dialog-form/style/css";
import "plus-pro-components/es/components/descriptions/style/css";
import Empty from "@/assets/common/empty.svg?component";
import UploadIcon from "~icons/ri/upload-2-line?width=26&height=26";
import AddFill from "~icons/ep/plus";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { setProductOrder } from "@/api/finance";
import { router } from "@/router";
import { getLotteryActInfo, addLotteryAct, setLotteryAct } from "@/api/lottery";

import {
  districtString,
  underscoreToCamel,
  fixImageUrl,
  handleImagesUpload,
  handleImagesUpload2
} from "@/utils/common";
import {
  PlusSearch,
  type PlusColumn,
  type FieldValues,
  PlusDialogForm
} from "plus-pro-components";
import {
  type Action,
  genFileId,
  ElMessageBox,
  ElMessage,
  UploadInstance,
  UploadRequestOptions,
  UploadProps,
  UploadRawFile
} from "element-plus";

defineOptions({
  name: "LotteryActivity"
});
const edit = ref(false);
const visible = ref(false);
const values = ref<FieldValues>({});

const searchColumns: PlusColumn[] = [
  {
    label: "选择时间范围",
    labelWidth: 120,
    width: 600,
    prop: "dateRange",
    valueType: "date-picker",
    tooltip: "请选择时间段",
    fieldProps: {
      type: "daterange",
      startPlaceholder: "开始时间",
      endPlaceholder: "结束时间",
      format: "YYYY-MM-DD HH:mm:ss",
      valueFormat: "YYYY-MM-DD HH:mm:ss"
    }
  },
  {
    label: "活动状态",
    width: 200,
    prop: "actStatus",
    valueType: "select",
    options: [
      {
        label: "未开始",
        value: 0
      },
      {
        label: "进行中",
        value: 1
      },
      {
        label: "已结束",
        value: 2
      }
    ]
  }
];

const rules = {
  endTime: [
    {
      required: false,
      message: "上机时间必填"
    }
  ],
  district: [
    {
      required: false,
      message: "地区运营商必选"
    }
  ]
};

const skus_columns: TableColumnList = [
  {
    label: "奖品名称",
    slot: "prizeName"
  },
  {
    label: "奖品图片",
    slot: "prizeImg"
  },
  {
    label: "奖品类型",
    slot: "prizeType"
  },
  {
    label: "剩余库存",
    slot: "remainStock"
  },
  {
    label: "总库存",
    slot: "totalStock"
  },
  {
    label: "排序",
    slot: "sortOrder"
  },
  {
    label: "状态",
    slot: "status"
  },
  {
    label: "概率",
    slot: "probability"
  },
  {
    label: "是否奖励",
    slot: "isWin"
  },
  {
    label: "操作",
    slot: "operation"
  }
];

const onAddPrize = () => {
  const data = {
    prizeName: "",
    prizeImg: "",
    prizeType: 1,
    status: 1,
    remainStock: 0,
    totalStock: 0,
    sortOrder: 0,

    isWin: 0
  };
  if (values.value.prizeList) {
    values.value.prizeList.push(data);
  } else {
    values.value.prizeList = [data];
  }
};

const onDelPrize = row => {
  const index = values.value.prizeList.indexOf(row);
  if (index !== -1) values.value.prizeList.splice(index, 1);
};

const formColumns: PlusColumn[] = [
  {
    label: "活动名称",
    width: 120,
    prop: "actName",
    valueType: "input"
  },
  {
    label: "活动图片",
    width: 120,
    prop: "actImg",
    valueType: "img",
    tooltip: "上传商品图片"
  },
  {
    label: "抽奖开始时间",
    prop: "startTime",
    width: 120,
    valueType: "date-picker",
    fieldProps: {
      type: "datetime",
      format: "YYYY-MM-DD HH:mm:ss",
      "value-format": "YYYY-MM-DD HH:mm:ss"
    },
    tooltip: "请输入抽奖开始时间"
  },
  {
    label: "抽奖结束时间",
    prop: "endTime",
    width: 120,
    valueType: "date-picker",
    fieldProps: {
      type: "datetime",
      format: "YYYY-MM-DD HH:mm:ss",
      "value-format": "YYYY-MM-DD HH:mm:ss"
    },
    tooltip: "请输入抽奖结束时间"
  },
  {
    label: "展示开始时间",
    prop: "showStartTime",
    width: 120,
    valueType: "date-picker",
    fieldProps: {
      type: "datetime",
      format: "YYYY-MM-DD HH:mm:ss",
      "value-format": "YYYY-MM-DD HH:mm:ss"
    },
    tooltip: "请输入展示开始时间"
  },
  {
    label: "展示结束时间",
    prop: "showEndTime",
    width: 120,
    valueType: "date-picker",
    fieldProps: {
      type: "datetime",
      format: "YYYY-MM-DD HH:mm:ss",
      "value-format": "YYYY-MM-DD HH:mm:ss"
    },
    tooltip: "请输入展示结束时间"
  },
  {
    label: "活动规则",
    width: 120,
    prop: "ruleText",
    valueType: "textarea"
  },
  {
    label: "活动权限",
    prop: "rulePerm",
    valueType: "select",
    options: [
      {
        label: "全员参与",
        value: "RULE_CONFIG_USER_ALL"
      },
      {
        label: "指定人员参与",
        value: "RULE_CONFIG_USER_ASSIGN"
      }
    ]
  },
  {
    label: "抽奖最大次数",
    hideInForm: computed(() => {
      return values.value.rulePerm == "RULE_CONFIG_USER_ASSIGN";
    }),
    prop: "max_total_user",
    fieldProps: {
      min: 0,
      step: 1
    },
    valueType: "input-number"
  },
  {
    label: "活动状态",
    prop: "actStatus",
    valueType: "select",
    options: [
      {
        label: "未开始",
        value: 0
      },
      {
        label: "进行中",
        value: 1
      },
      {
        label: "已结束",
        value: 2
      }
    ]
  },
  {
    label: "排序",
    prop: "sortOrder",
    fieldProps: {
      min: 0,
      step: 1
    },
    valueType: "input-number"
  },
  {
    label: "奖品列表",
    width: 120,
    prop: "prizeList"
  }
];

const {
  loading,
  columns,
  dataList,
  pagination,
  loadingConfig,
  adaptiveConfig,
  onKeywordChange,
  onSizeChange,
  loadData,
  onCurrentChange
} = useColumns();
// if (!props.delete && !props.edit && !props.ship) {
//   columns.pop();
// }
function infoClick(row) {
  router.push({ name: "OperateLotteryDetail", query: { id: row.actId } });
}
const editClick = async row => {
  console.log(
    "%crow===编辑>>>: ",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    row
  );
  try {
    const res = await getLotteryActInfo({ actId: row.actId });

    Object.assign(values.value, res.data);
    const ruleConfig = JSON.parse(res.data.ruleConfig);
    values.value.rulePerm = ruleConfig.userType;
    values.value.max_total_user = ruleConfig.max_total_user;
    // 转换成字number
    values.value.prizeList.forEach((item: any) => {
      item.probability = Number(item.probability);
      item.sortOrder = Number(item.sortOrder);
    });

    console.log(
      "%cres===>>>",
      "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
      "返回的",
      res,
      values.value
    );
    edit.value = true;
    visible.value = true;
  } catch (error) {
    console.log(error, "error");
  }
};
const addClick = () => {
  console.log("%c点击了添加商品>>>: ", "color: MidnightBlue; font-size: 20px;");
  // ElMessage.info("暂未开发该功能");
  // return;
  edit.value = false;
  values.value = { prizeList: [] };
  visible.value = true;
};
const confirmLoading = ref(false);
const handleSubmit = async (value: FieldValues) => {
  const updatedValues = { ...value };
  confirmLoading.value = true;

  const ruleConfig = {
    userType: updatedValues.rulePerm,
    max_total_user: updatedValues.max_total_user
  };

  updatedValues.rulePerm = undefined;
  updatedValues.max_total_user = undefined;
  // 转换成字符串
  updatedValues.prizeList.forEach((item: any) => {
    item.probability = item.probability.toString();
    item.sortOrder = item.sortOrder.toString();
  });

  if (edit.value) {
    try {
      const params = {
        actId: updatedValues.actId,
        actName: updatedValues.actName,
        actImg: updatedValues.actImg,
        startTime: updatedValues.startTime,
        endTime: updatedValues.endTime,
        ruleConfig,
        actStatus: updatedValues.actStatus,
        showStartTime: updatedValues.showStartTime,
        showEndTime: updatedValues.showEndTime,
        ruleText: updatedValues.ruleText,
        prizeList: updatedValues.prizeList
      };
      await setLotteryAct(params);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      loadData();
      ElMessage.success("修改成功");
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  } else {
    try {
      updatedValues.ruleConfig = ruleConfig;
      await addLotteryAct(updatedValues);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      loadData();
      ElMessage.success("添加成功");
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  }
};

const handleSearch = (value: any) => {
  console.log(value, "search");
  onKeywordChange(value);
};
const handleReset = value => {
  console.log("reset", value);
  onKeywordChange(value);
};
const handleChange = (value: any, target: any) => {
  console.log("change", value);

  onKeywordChange(value);
};
const formRef = ref();
const defaultSearchState = ref({});

const imageFile = (path: any) => {
  return path.split(",").map((path: any) => {
    return { url: fixImageUrl(path), name: path.split("/").pop() };
  });
};
const productImageRef = ref<UploadInstance>();
const prizeImageRef = ref<UploadInstance>();
const handleIconImageSuccess: UploadProps["onSuccess"] = (res, file) => {
  console.log("iconsucc", "color: MidnightBlue; font-size: 20px;", file, res);
  values.value.actImg = res.data;
};
const handleIconImageRemove: UploadProps["onRemove"] = (file, files) => {
  values.value.actImg = undefined;
  console.log(
    "%cfile===>>>",
    "color: MidnightBlue; font-size: 20px;",
    file,
    files
  );
};
/// 超出limit限制 先清空文件列表再执行上传
const handleIconImageExceed: UploadProps["onExceed"] = files => {
  productImageRef.value?.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  productImageRef.value?.handleStart(file);
  productImageRef.value?.submit();
};

const handlePrizeImageSuccess = (res, file, files, index) => {
  console.log("tttttt");
  console.log(res, file, files, index);
  values.value.prizeList[index].prizeImg = res.data;

  // for (let i = 0; i < values.value.prizeList.length; i++) {
  //   const imageUrl = files[i].response ? files[i].response.data : files[i].url;
  //   values.value.prizeList[i].prizeImg = imageUrl;
  // }
  // values.value.iconimage = res.data;
};
const handlePrizeImageRemove = (file, files, index) => {
  console.log("remvoe", file, files);
  values.value.prizeList[index].prizeImg = undefined;
};
/// 超出limit限制 先清空文件列表再执行上传
const handlePrizeImageExceed: UploadProps["onExceed"] = (files, upFiles) => {
  console.log(files, upFiles);
  ElMessage.error("请先删除后再选择图片");
  // productImageRef.value?.clearFiles();
  // const file = files[0] as UploadRawFile;
  // file.uid = genFileId();
  // productImageRef.value?.handleStart(file);
  // productImageRef.value?.submit();
};

const previewImageUrl = ref();
const previewImageName = ref();
const showPreviewImage = ref(false);
const handlePreviewImage: UploadProps["onPreview"] = file => {
  previewImageName.value = file.name;
  previewImageUrl.value = file.url;
  showPreviewImage.value = true;
};
</script>

<template>
  <div class="flex flex-col">
    <ElPageHeader :icon="null">
      <template #title>
        <h3>抽奖活动</h3>
      </template>
      <template #extra>
        <div class="flex flex-row items-end justify-end mb-4">
          <el-button type="primary" @click="addClick">
            <el-icon :size="15" color="#fff">
              <IconifyIconOffline :icon="Plus" />
            </el-icon>
            添加抽奖
          </el-button>
        </div>
      </template>
      <PlusSearch
        :defaultValues="defaultSearchState"
        class="mt-5"
        :columns="searchColumns"
        :hasUnfold="false"
        @reset="handleReset"
        @search="handleSearch"
        @change="handleChange"
      />
    </ElPageHeader>

    <pure-table
      ref="tableRef"
      showOverflowTooltip
      class="mt-2"
      border
      adaptive
      :adaptiveConfig="adaptiveConfig"
      row-key="actId"
      alignWhole="center"
      :loading="loading"
      :loading-config="loadingConfig"
      :data="dataList"
      :columns="columns"
      :pagination="pagination"
      @page-size-change="onSizeChange"
      @page-current-change="onCurrentChange"
    >
      <template #actImg="{ row, index }">
        <el-image
          preview-teleported
          loading="lazy"
          :src="fixImageUrl(row.actImg)"
          :preview-src-list="dataList.map(v => fixImageUrl(v.actImg))"
          :initial-index="index"
          fit="cover"
          class="w-[50px] h-[50px]"
        />
      </template>

      <template #operation="{ row }">
        <el-button type="primary" size="small" @click="editClick(row)"
          >编辑</el-button
        >
        <el-button type="info" size="small" @click="infoClick(row)">
          详情
        </el-button>
      </template>
    </pure-table>
    <PlusDialogForm
      ref="formRef"
      v-model:visible="visible"
      v-model="values"
      :form="{ columns: formColumns, rules, labelWidth: 120 }"
      :dialog="{ confirmLoading, width: '80%' }"
      :title="edit ? '编辑抽奖' : '添加抽奖'"
      @confirm="handleSubmit"
    >
      <template #plus-field-actImg>
        <el-upload
          ref="productImageRef"
          drag
          :auto-upload="true"
          list-type="picture-card"
          :limit="1"
          :http-request="handleImagesUpload"
          :file-list="
            values.actImg && values.actImg.length > 0
              ? imageFile(values.actImg)
              : []
          "
          :on-success="handleIconImageSuccess"
          :on-remove="handleIconImageRemove"
          :on-preview="handlePreviewImage"
          :on-exceed="handleIconImageExceed"
        >
          <div>
            <UploadIcon class="m-auto mb-2" />
            可点击或拖拽上传
          </div>
        </el-upload>
      </template>

      <template #plus-field-prizeList>
        <pure-table
          border
          row-key="prizeId"
          align-whole="center"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          :data="values.prizeList"
          :columns="skus_columns"
        >
          <template #empty>
            <Empty fill="var(--el-svg-monochrome-grey)" class="m-auto" />
          </template>
          <template #append>
            <el-button
              type="success"
              class="w-full my-2!"
              :icon="useRenderIcon(AddFill)"
              @click="onAddPrize"
            >
              添加一行数据
            </el-button>
          </template>
          <template #prizeName="{ row }">
            <el-input
              v-model="row.prizeName"
              placeholder="请输入奖品名称"
              style="width: 100%"
            />
          </template>
          <template #prizeType="{ row }">
            <el-select v-model="row.prizeType" placeholder="请选择奖品类型">
              <el-option label="实物" :value="1" />
              <el-option label="虚拟" :value="2" />
              <el-option label="谢谢参与" :value="3" />
            </el-select>
          </template>

          <template #prizeCode="{ row }">
            <el-input
              v-model="row.prizeCode"
              placeholder="请输入奖品编码"
              style="width: 100%"
            />
          </template>

          <template #prizeImg="{ row, index }">
            <el-upload
              :http-request="handleImagesUpload"
              :auto-upload="true"
              :show-file-list="true"
              list-type="picture"
              :limit="1"
              :file-list="
                row.prizeImg && row.prizeImg.length > 0
                  ? imageFile(row.prizeImg)
                  : []
              "
              :on-success="
                (res, file, files) =>
                  handlePrizeImageSuccess(res, file, files, index)
              "
              :on-remove="
                (file, files) => handlePrizeImageRemove(file, files, index)
              "
              :on-preview="handlePreviewImage"
              :on-exceed="handlePrizeImageExceed"
            >
              <el-button
                v-if="!row.prizeImg || row.prizeImg.length == 0"
                size="small"
                type="primary"
                >选择图片</el-button
              >
            </el-upload>
          </template>
          <template #isWin="{ row }">
            <el-radio-group v-model="row.isWin">
              <el-radio-button :value="1" label="是" />
              <el-radio-button :value="0" label="否" />
            </el-radio-group>
          </template>

          <template #remainStock="{ row }">
            <el-input-number
              v-model="row.remainStock"
              :precision="0"
              :step="1"
              :min="0"
              placeholder="请输入剩余库存"
              style="width: 100%"
            />
          </template>
          <template #totalStock="{ row }">
            <el-input-number
              v-model="row.totalStock"
              :precision="0"
              :step="1"
              :min="-1"
              placeholder="请输入库存"
              style="width: 100%"
            />
          </template>
          <template #probability="{ row }">
            <el-input-number
              v-model="row.probability"
              :precision="2"
              :step="0.01"
              :min="0"
              placeholder="请输入中奖概率"
              style="width: 100%"
            />
          </template>

          <template #status="{ row }">
            <el-radio-group v-model="row.status">
              <el-radio-button :value="1" label="启用" />
              <el-radio-button :value="2" label="关闭" />
            </el-radio-group>
          </template>
          <template #sortOrder="{ row }">
            <el-input-number
              v-model="row.sortOrder"
              :precision="0"
              :step="1"
              :min="0"
              placeholder="请输入排序"
              style="width: 100%"
            />
          </template>
          <template #operation="{ row }">
            <el-button
              v-if="!edit"
              class="reset-margin"
              type="danger"
              :icon="useRenderIcon(Delete)"
              @click="onDelPrize(row)"
            />
            <view v-else>无</view>
          </template>
        </pure-table>
      </template>
    </PlusDialogForm>
    <el-dialog v-model="showPreviewImage">
      <img w-full :src="previewImageUrl" :alt="previewImageName" />
    </el-dialog>
  </div>
</template>

<style scoped>
::deep .wot-message-box__icon--warning {
  --el-messagebox-color: red;
  color: red !important;
  fill: red !important;
}
</style>
